package wwk.common.event;

import java.util.ArrayList;
import java.util.HashMap;

import wwk.common.constant.Commonstant;

import android.os.Handler;
import android.os.Message;

public class MessageManager 
{
	private static MessageManager notificationCenter=null;
	
	private HashMap<String,ArrayList<Handler>> messageHandlerMap=
			new HashMap<String,ArrayList<Handler>>();
	
	public static MessageManager instance()
	{
		if(notificationCenter==null)
		{
			notificationCenter=new MessageManager();
		}
		
		return notificationCenter;
	}
	
	private MessageManager()
	{
		
	}
	
	public void addHandler(Handler handler,int messageType)
	{
		String key=""+messageType;
		
		ArrayList<Handler> handlerList=null;
		
		if(messageHandlerMap.containsKey(key))
		{
			handlerList=messageHandlerMap.get(key);
		}
		else
		{
			handlerList=new ArrayList<Handler>();
			messageHandlerMap.put(key, handlerList);
		}
		
		handlerList.add(handler);
	}
	
	public void removeHandler(Handler handler,int messageType)
	{
		String key=""+messageType;

		if(messageHandlerMap.containsKey(key))
		{
			ArrayList<Handler> handlerList=messageHandlerMap.get(key);
			handlerList.remove(handler);
		}
	}
	
	public void sendMessage(int messageType)
	{
		String key=""+messageType;

		if(messageHandlerMap.containsKey(key))
		{
			ArrayList<Handler> handlerList=messageHandlerMap.get(key);
			for(Handler handler:handlerList)
			{
				handler.sendEmptyMessage(messageType);
			}
		}
	}
	
	public void sendMessage(int messageType,Object obj)
	{
		String key=""+messageType;

		if(messageHandlerMap.containsKey(key))
		{
			Message msg = new Message();
			msg.what = messageType;
			msg.obj = obj;
			
			ArrayList<Handler> handlerList=messageHandlerMap.get(key);
			for(Handler handler:handlerList)
			{
				handler.sendMessage(msg);
			}
		}
	}
}
